package org.poit.controller;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

@Controller
public class POIController {

    @GetMapping({"/", "/index"})
    @ResponseBody
    public String index(HttpServletResponse response, HttpServletRequest request) throws IOException {

        Workbook wb = new HSSFWorkbook();
        Sheet sheet = wb.createSheet("test sheet");
        Row row = sheet.createRow(0);
        row.createCell(0).setCellValue("test cell");


        File file = new File("workbook.xlsx");

        try (OutputStream fileOut = new FileOutputStream(file)) {
            wb.write(fileOut);
            wb.close();

            InputStream is = new FileInputStream(file);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            byte[] bytes = new byte[1024];
            int len = -1;
            while ((len = is.read()) > 0) {
                baos.write(bytes, 0, len);
            }
            ServletOutputStream os = response.getOutputStream();
            baos.writeTo(os);
            os.close();
            baos.close();
        }


        return "index";
    }
}
